<?php
namespace app\api\controller;
header('content-type:application:json;charset=utf8');  
header('Access-Control-Allow-Origin:*');  
header('Access-Control-Allow-Credentials:true');  
header('Access-Control-Allow-Methods:*');  
header('Access-Control-Allow-Headers:x-requested-with,content-type'); 
use app\common\controller\Api;
use wechat\WechatOauth;
use think\Db;
use think\Session;
use think\Cache;

/**
 * @title 微信授权登录
 */
class Oauth extends Api{
    
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';


    /**
     * @title 微信授权获取用户信息接口
     * @url /api/Oauth/WechatOauth
     * @method post
     * @param code:参数code
     * @return data:用户ID
     */
    public function WechatOauth($code){
        $wchat = new WechatOauth;
        //$code = request()->param('code',"");
        $user = $wchat->getUserAccessUserInfo($code);
        $useropenid = Db::name('user')->field('id,openid')->where(['openid'=>$user['openid']])->find();
        $time = strtotime(date('Y-m-d H:i:s'));
        if($useropenid){
             $userdata = [
                 'updatetime' => $time,
             ];
             $update = Db::name('user')->where(['openid'=>$useropenid['openid']])->update($userdata);
             Cache::set('userid'.$useropenid['id'],$useropenid['id'],1800);
             $arr['data'] = $useropenid['id'];
             return json($arr);
             //$this->success('授权成功',$useropenid['id'],'200','jsonp');
        }else{
            $userdata = [
                'username' => $user['nickname'],
                'image' => $user['headimgurl'],
                'openid' => $user['openid'],
                'code' => $this->GetNumber(),
                'createtime' => $time,
                'updatetime' => $time,
            ];
            $userinsert = Db::name('user')->insertGetId($userdata);
            Cache::set('userid'.$userinsert,(int)$userinsert,1800);
            $arr['data'] = (int)$userinsert;
            return json($arr);
            //$this->success('授权成功',(int)$userinsert,'200','jsonp');
        }
    }

    private function GetNumber(){
        $yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z');
        $orderSn = $yCode[abs(intval(date('d')) - 8)] . substr(time(), -4) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));
        $where['code']= $orderSn;
        $code = Db::name('user')->field('code')->where($where)->find();
        if($code){
            $ordercode = $this->GetNumber();
        }else{
            $ordercode = $orderSn;
        }
        return $ordercode;
    }


}




?>